const express = require('express');

// 创建三个测试服务器实例
function createTestServer(name, port) {
  const app = express();
  app.use(express.json());

  // 添加日志中间件
  app.use((req, res, next) => {
    console.log(`[${name}:${port}] ${new Date().toISOString()} - ${req.method} ${req.url}`);
    next();
  });

  // 健康检查端点
  app.get('/health', (req, res) => {
    res.json({ status: 'healthy', server: name, port, timestamp: new Date().toISOString() });
  });

  // 主页
  app.get('/', (req, res) => {
    res.json({ 
      message: `欢迎访问${name}`, 
      server: name,
      port,
      timestamp: new Date().toISOString(),
      clientIP: req.ip
    });
  });

  // API端点
  app.get('/api/users', (req, res) => {
    const users = {
      server1: [{ id: 1, name: '张三', server: name }, { id: 2, name: '李四', server: name }],
      server2: [{ id: 3, name: '王五', server: name }, { id: 4, name: '赵六', server: name }],
      server3: [{ id: 5, name: '孙七', server: name }, { id: 6, name: '周八', server: name }]
    };
    res.json(users[name] || []);
  });

  app.get('/api/status', (req, res) => {
    res.json({
      server: name,
      port,
      uptime: process.uptime(),
      memory: process.memoryUsage(),
      timestamp: new Date().toISOString()
    });
  });

  // 启动服务器
  const server = app.listen(port, '0.0.0.0', () => {
    console.log(`${name} 运行在 http://0.0.0.0:${port}`);
  });

  return server;
}

// 启动三个测试服务器
const servers = [
  createTestServer('server1', 3001),
  createTestServer('server2', 3002),
  createTestServer('server3', 3003)
];

console.log('\n=== 测试服务器已启动 ===');
console.log('现在可以在FRP Manager中配置代理规则：');
console.log('1. 创建HTTP代理规则，远程端口如8080');
console.log('2. 添加后端服务器: localhost:3001, localhost:3002, localhost:3003');
console.log('3. 启动代理规则');
console.log('4. 访问 http://localhost:8080 测试负载均衡');
console.log('\n测试端点:');
console.log('  GET / - 查看当前处理请求的服务器');
console.log('  GET /health - 健康检查');
console.log('  GET /api/users - 用户数据');
console.log('  GET /api/status - 服务器状态');

// 优雅退出处理
process.on('SIGINT', () => {
  console.log('\n正在关闭测试服务器...');
  servers.forEach(server => server.close());
  process.exit(0);
});